import { NestFactory } from '@nestjs/core';
import { RootModule } from './app.module';
import { ValidationPipe, VersioningType } from '@nestjs/common';
import { ResponseInterceptor } from './pipe/response';
import { AllExceptionFilter } from './pipe/exception';
import { RequestInterceptor } from './pipe/request';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { NoAuthGuard } from './common/any.strategy';
import config from './config';
import * as serveStatic from 'serve-static';
import { join } from 'path';
import { LoggerService } from './common/modules/logger/logger.service';
import { RedisIoAdapter } from './app/modules/websocket/webscoket.adapter';
import { repl } from '@nestjs/core';


process.on('uncaughtException', (error) => {
	if(!config.isServer){
		console.error('Uncaught Exception:', error);
	}
});

const fs=require('fs')

async function bootstrap() {
	const app = await NestFactory.create(RootModule);

	const extractor = (request: Request): string | string[] =>{
		if(!request.headers["api-version"]){
			request.headers["api-version"]="1"
		}
		return request.headers["api-version"]
	}

	app.enableVersioning({
		type: VersioningType.CUSTOM,
		extractor,
	});

	// 允许cors
	app.enableCors();

	// 全局使用管道
	app.useGlobalPipes(new ValidationPipe({
		transform: true
	}));
	// 全局拦截器
	app.useGlobalInterceptors(new ResponseInterceptor());
	// 全局注册请求过滤器
	app.useGlobalInterceptors(new RequestInterceptor(app.get(LoggerService)));
	// 全局注册错误的过滤器
	app.useGlobalFilters(new AllExceptionFilter(app.get(LoggerService)));
	// 全局守卫
	app.useGlobalGuards(new NoAuthGuard())

	if(config.env=="dev"||config.env=="pre"||config.env=="test"){
		// 创建swagger文档
		const options = new DocumentBuilder()
		.setTitle("SANGUO-BACKEND")
		.setDescription(`The SANGUO-BACKEND API description`)
		.setVersion("1.0.0")
		.addBearerAuth()
		.build();
		const document = SwaggerModule.createDocument(app, options);
		fs.writeFileSync("./swagger-spec.json", JSON.stringify(document));
		SwaggerModule.setup('api-doc', app, document);
	}

	if(config.env=="dev"||config.env=="pre"||config.env=="test"){
		// 静态目录
		app.use('/static', serveStatic(join(__dirname, '../static/')));
	}


	const redisIoAdapter = new RedisIoAdapter(app);
	await redisIoAdapter.connectToRedis();
	app.useWebSocketAdapter(redisIoAdapter);

	await app.listen(13000);


	// if(!config.isServer){
	// 	await repl(RootModule);
	// }

}
bootstrap();
